package zkp

import (
	"github.com/consensys/gnark/frontend"
)

// AuthCircuit 定义认证电路
type AuthCircuit struct {
	// 私有输入
	Secret frontend.Variable `gnark:",secret"`

	// 公开输入
	DeviceID   frontend.Variable `gnark:",public"`
	Challenge  frontend.Variable `gnark:",public"`
	Commitment frontend.Variable `gnark:",public"`
	Response   frontend.Variable `gnark:",public"`
}

// Define 定义电路逻辑
func (circuit *AuthCircuit) Define(api frontend.API) error {
	// 计算 commitment = MiMC(secret, device_id)
	computedCommitment := mimcHash(api, circuit.Secret, circuit.DeviceID)

	// 计算 response = MiMC(secret, challenge)
	computedResponse := mimcHash(api, circuit.Secret, circuit.Challenge)

	// 验证 commitment 匹配
	api.AssertIsEqual(circuit.Commitment, computedCommitment)

	// 验证 response 匹配
	api.AssertIsEqual(circuit.Response, computedResponse)

	return nil
}

// mimcHash 在电路中实现 MiMC 哈希
func mimcHash(api frontend.API, key frontend.Variable, data frontend.Variable) frontend.Variable {
	// 使用 gnark 内置的 MiMC 哈希
	mimc, err := frontend.NewMiMC(api)
	if err != nil {
		panic(err)
	}

	mimc.Write(key, data)
	return mimc.Sum()
}
